import React, {Component} from 'react';
import {Button, Form, Input, Row, Col, Table, DatePicker, Pagination} from 'antd';
import moment from 'moment';
import {statistics, excel} from "../value";
import app from '../AppMethod';
import {config} from "../config";
import {Consumer} from "../store";

const FormItem = Form.Item;
const RangePicker = DatePicker.RangePicker;

class consignmentStatistic extends Component {
    constructor(props) {
        super(props);
        this.state = {
            loading: false,
            pagination: {
                current: 0,
                total: 0,
                pagination: 0
            },
            allPage: 0,
            data: [],
            searchData: {}
        };
    };

    columns = [
        {
            title: '托运公司',
            dataIndex: 'car_logistics_name',
        },
        {
            title: '订单数量',
            dataIndex: 'total_output',
        },
        {
            title: '订单金额',
            dataIndex: 'total_money',
        },
        {
            title: '总件数',
            dataIndex: 'total_package',
        },
        {
            title: '总散件数',
            dataIndex: 'total_parts',
        },
        {
            title: '总费用',
            dataIndex: 'total_pay',
        }
    ];

    render() {
        return (
            <div>
                <Row>
                    <SearchLists
                        clickSearch={(value) => {
                            this.handleGetSearch(value)
                        }}
                        handleReset={() => this.handleReset()}
                        handleExport={(values) => this.handleExport(values)}
                    >
                    </SearchLists>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Table
                        columns={this.columns}
                        rowKey={(record, index) => index}
                        dataSource={this.state.data}
                        loading={this.state.loading}
                        pagination={false}
                    >
                    </Table>
                </Row>
                <Row style={{marginTop: '20px'}}>
                    <Col span={12} style={{fontSize: '15px'}}>
                        共 {this.state.pagination.total} 条记录 第 {this.state.pagination.current} / {this.state.allPage}
                        页
                    </Col>
                    <Col span={12} style={{textAlign: 'right'}}>
                        <Pagination {...this.state.pagination} showSizeChanger={true} showQuickJumper={true}
                                    hideOnSinglePage={false}
                                    onChange={(page, pageSize) => this.handlePageChange(page, pageSize)}
                                    onShowSizeChange={(current, size) => this.handleSizeChange(current, size)}/>
                    </Col>
                </Row>
            </div>
        )
    };

    componentDidMount() {
        const {dispatch} = this.props;
        dispatch({menuType: "托运数据统计"});
        this.handleGetConsignList();
    };

    componentWillUnmount() {
        this.setState = (count, callback) => {
            return;
        }
    };

    /**
     * 获取托运数据列表
     * @param data
     */
    handleGetConsignList(data = {page: 1, size: 10}) {
        this.setState({loading: true});
        app.post(statistics.TOTAL_CONSIGNSTATISTICS, data).then((result) => {
            if (result.code === 1) {
                let count = result.data.count;
                let pagination = {
                    current: data.page,
                    pageSize: data.size,
                    total: count
                };
                let allPage;
                if (count % data.size > 0) {
                    allPage = parseInt(count / data.size) + 1;
                } else {
                    allPage = count / data.size;
                }
                this.setState({allPage, pagination});
                let carData = result.data.dataSet;
                this.setState({data: carData, loading: false});
            } else {
                let pagination = {
                    current: 0,
                    pageSize: 0,
                    total: 0
                };
                let allPage = 0;
                this.setState({data: [], loading: false, pagination, allPage});
            }
        })
    };

    /**
     * 根据条件查询托运数据列表
     * @param value
     */
    handleGetSearch(value) {
        let times = value.date;
        let date_start = undefined;
        let date_end = undefined;
        if (times != undefined && times.length > 0) {
            date_start = moment(times[0]._d).format('YYYY-MM-DD');
            date_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let tempData = {
            date_start: date_start,
            date_end: date_end,
            car_logistics_name: value.car_logistics_name
        };
        this.setState({searchData: tempData});
        let searchData = tempData;
        searchData.page = 1;
        searchData.size = this.state.pagination.pageSize || 10;
        this.handleGetConsignList(searchData);
    };

    /**
     * 处理重置按钮事件
     */
    handleReset() {
        this.setState({searchData: {}});
        this.handleGetConsignList();
    };

    /**
     * 处理分页跳转事件
     * @param page
     * @param size
     */
    handlePageChange(page, size) {
        let data = this.state.searchData;
        data.page = page;
        data.size = size;
        this.handleGetConsignList(data);
    };

    /**
     * 处理页数变化事件
     * @param current
     * @param size
     */
    handleSizeChange(current, size) {
        let data = this.state.searchData;
        data.page = current;
        data.size = size;
        this.handleGetConsignList(data);
    };

    /**
     * 处理导出Excel事件
     * @param value
     */
    handleExport(value) {
        let times = value.date;
        let date_start = undefined;
        let date_end = undefined;
        if (times != undefined && times.length > 0) {
            date_start = moment(times[0]._d).format('YYYY-MM-DD');
            date_end = moment(times[1]._d).format('YYYY-MM-DD');
        }
        let tempData = {
            date_start: date_start,
            date_end: date_end,
            car_logistics_name: value.car_logistics_name
        };
        let params = app.getParams(tempData);
        if (params.length > 0) {
            window.location.href = config.serverUrl + excel.EXPORT_CONSIGNSTATISTICS + '?' + params;
        } else {
            window.location.href = config.serverUrl + excel.EXPORT_CONSIGNSTATISTICS;
        }
    }
};

class SearchList extends Component {
    constructor(props) {
        super(props);
        this.state = {}
    };

    formItemLayout = {
        labelCol: {span: 8},
        wrapperCol: {span: 12},
    };

    render() {
        const {getFieldDecorator} = this.props.form;
        return (
            <div>
                <Row>
                    <Form className="login-form">
                        <Col span={6}>
                            <FormItem label="托运公司" {...this.formItemLayout}>
                                {
                                    getFieldDecorator('car_logistics_name')(
                                        <Input type="text" placeholder="请输入"
                                               onPressEnter={() => this.handleOnPressEnter()}/>
                                    )
                                }
                            </FormItem>
                        </Col>
                        <Col span={8}>
                            <FormItem label="选择日期" {...this.formItemLayout}>
                                {
                                    getFieldDecorator('date')(
                                        <RangePicker
                                            ranges={{
                                                Today: [moment(), moment()],
                                                'This Month': [moment(), moment().endOf('month')]
                                            }}
                                            format="YYYY/MM/DD"
                                            onChange={(dates, dateStrings) => this.handleTimeOnChange(dates, dateStrings)}
                                        />
                                    )
                                }
                            </FormItem>
                        </Col>
                        <Col offset={4} span={6} style={{float: 'right'}}>
                            <Button type="primary"
                                    onClick={() => this.handleSearchComplain()}
                            >
                                查询
                            </Button>
                            <Button type="default"
                                    onClick={() => this.handleReset()}
                                    style={{marginLeft: '10px'}}
                            >
                                重置
                            </Button>
                        </Col>
                    </Form>
                </Row>
                <Row>
                    <Button type="primary" onClick={() => this.handleExport()}>导出Excel</Button>
                </Row>
            </div>
        )
    };

    componentDidMount() {

    };

    /**
     * 获取查询条件
     */
    handleSearchComplain() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.clickSearch(values);
            }
        })
    };

    /**
     * 重置按钮事件
     */
    handleReset() {
        this.props.form.resetFields();
        this.props.handleReset();
    };

    /**
     * 获取导出Excel的条件
     */
    handleExport() {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                this.props.handleExport(values);
            }
        })
    };

    /**
     * 处理输入框按下回车键的事件
     */
    handleOnPressEnter() {
        //调用获取搜索条件的函数
        this.handleSearchComplain();
    };

    /**
     * 处理日期选择框变化事件
     */
    handleTimeOnChange(dates, dateStrings) {
        this.props.form.validateFields((err, values) => {
            if (!err) {
                values.date = dates;
                this.props.clickSearch(values);
            }
        })
    };
}

const SearchLists = Form.create()(SearchList);
const ConsignmentStatistics = Form.create()(consignmentStatistic);
export default prop => (
    <Consumer>
        {
            props => (
                <ConsignmentStatistics {...prop} {...props}/>
            )
        }
    </Consumer>
);